<script setup>
import { ref, onMounted, reactive } from 'vue'
import { fetchLogList } from '@/api/logApi'
import { Search, RefreshRight } from '@element-plus/icons-vue'
import { formatDateTime } from '@/utils/dayjs'
import { ElMessage } from 'element-plus'

// 查询条件
const queryForm = reactive({
  module: '',
  operationTimeBegin: '',
  operationTimeEnd: '',
  dealer: '',
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 15,
  total: 0,
})

// 表格数据
const tableData = ref([])

// 加载状态
const loading = ref(false)

// 日期快捷选项
const shortcuts = [
  {
    text: '今天',
    value: () => {
      const now = new Date()
      const start = new Date(now.getFullYear(), now.getMonth(), now.getDate())
      const end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59)
      return [start, end]
    },
  },
  {
    text: '昨天',
    value: () => {
      const now = new Date()
      const start = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1)
      const end = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1, 23, 59, 59)
      return [start, end]
    },
  },
  {
    text: '最近7天',
    value: () => {
      const now = new Date()
      const start = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
      return [start, now]
    },
  },
  {
    text: '最近30天',
    value: () => {
      const now = new Date()
      const start = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000)
      return [start, now]
    },
  },
]

// 操作时间范围
const operationTimeRange = ref([])

// 获取日志列表
const fetchLogData = async () => {
  try {
    loading.value = true

    // 处理时间范围
    let timeParams = {}
    if (operationTimeRange.value && operationTimeRange.value.length === 2) {
      timeParams.operationTimeBegin = formatDateTime(
        operationTimeRange.value[0],
        'YYYY-MM-DD HH:mm:ss',
      )
      timeParams.operationTimeEnd = formatDateTime(
        operationTimeRange.value[1],
        'YYYY-MM-DD HH:mm:ss',
      )
    }

    const requestData = {
      queryFields: {
        module: queryForm.module,
        dealer: queryForm.dealer,
        ...timeParams,
      },
      currentPage: pagination.currentPage - 1, // 后端页码从0开始
      pageSize: pagination.pageSize,
    }

    const res = await fetchLogList(requestData)

    if (res.success) {
      tableData.value = res.data?.list || []
      pagination.total = res.data?.total || 0
    } else {
      ElMessage.error(res.msg || '获取日志列表失败')
      tableData.value = []
      pagination.total = 0
    }
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchLogData()
}

// 重置
const handleReset = () => {
  queryForm.module = ''
  queryForm.dealer = ''
  operationTimeRange.value = []
  pagination.currentPage = 1
  fetchLogData()
}

// 分页改变
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchLogData()
}

// 页面大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  fetchLogData()
}

// 格式化执行时间
const formatExecutionTime = (time) => {
  if (time < 1000) return `${time}ms`
  return `${(time / 1000).toFixed(2)}s`
}

// 详情对话框相关
const detailDialogVisible = ref(false)
const currentLogDetail = ref(null)

// 查看详情
const handleViewDetail = (row) => {
  currentLogDetail.value = row
  detailDialogVisible.value = true
}

// 关闭详情对话框
const closeDetailDialog = () => {
  detailDialogVisible.value = false
  currentLogDetail.value = null
}

// 格式化JSON数据
const formatJson = (jsonStr) => {
  if (!jsonStr) return ''
  try {
    const parsed = JSON.parse(jsonStr)
    return JSON.stringify(parsed, null, 2)
  } catch {
    return jsonStr
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchLogData()
})
</script>

<template>
  <!-- 详情对话框 -->
  <el-dialog
    v-model="detailDialogVisible"
    title="日志详情"
    width="50%"
    align-center
    destroy-on-close
    :before-close="closeDetailDialog"
  >
    <div v-if="currentLogDetail" class="log-detail">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="模块">
          {{ currentLogDetail.module }}
        </el-descriptions-item>
        <el-descriptions-item label="操作描述">
          {{ currentLogDetail.description }}
        </el-descriptions-item>
        <el-descriptions-item label="IP地址">
          {{ currentLogDetail.ip }}
        </el-descriptions-item>
        <el-descriptions-item label="操作人员">
          {{ currentLogDetail.operator }}
        </el-descriptions-item>
        <el-descriptions-item label="执行时间">
          <span :class="{ 'slow-request': currentLogDetail.executionTime > 3000 }">
            {{ formatExecutionTime(currentLogDetail.executionTime) }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="操作时间" :span="2">
          {{ formatDateTime(currentLogDetail.operationTime) }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- 错误信息 -->
      <div class="detail-section">
        <h4>错误信息</h4>
        <el-input
          type="textarea"
          :model-value="currentLogDetail.errorMsg || '无'"
          readonly
          :rows="4"
          :class="['error-textarea', { 'has-error': currentLogDetail.errorMsg }]"
        />
      </div>

      <!-- 请求参数 -->
      <div class="detail-section" v-if="currentLogDetail.requestParams">
        <h4>请求参数</h4>
        <el-input
          type="textarea"
          :model-value="formatJson(currentLogDetail.requestParams)"
          readonly
          :rows="8"
          class="json-textarea"
        />
      </div>

      <!-- 响应结果 -->
      <div class="detail-section" v-if="currentLogDetail.responseResult">
        <h4>响应结果</h4>
        <el-input
          type="textarea"
          :model-value="formatJson(currentLogDetail.responseResult)"
          readonly
          :rows="8"
          class="json-textarea"
        />
      </div>
    </div>

    <template #footer>
      <el-button @click="closeDetailDialog">关闭</el-button>
    </template>
  </el-dialog>

  <div class="log-container">
    <!-- 搜索条件区域 -->
    <div class="controller-container">
      <el-form :model="queryForm" inline>
        <el-form-item label="模块">
          <el-input
            v-model="queryForm.module"
            placeholder="请输入模块名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="操作人员">
          <el-input
            v-model="queryForm.dealer"
            placeholder="请输入操作人员"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="操作时间">
          <el-date-picker
            v-model="operationTimeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :shortcuts="shortcuts"
            style="width: 360px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <template #icon>
              <el-icon><Search /></el-icon>
            </template>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <template #icon>
              <el-icon><RefreshRight /></el-icon>
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table v-loading="loading" :data="tableData" style="width: 100%" height="100%" stripe>
        <el-table-column prop="module" label="模块" min-width="180" />

        <el-table-column
          prop="description"
          label="操作描述"
          min-width="180"
          show-overflow-tooltip
        />

        <el-table-column prop="ip" label="IP地址" width="140" />

        <el-table-column prop="operator" label="操作人员" width="120" />

        <el-table-column label="执行时间" width="100">
          <template #default="{ row }">
            <span :class="{ 'slow-request': row.executionTime > 3000 }">
              {{ formatExecutionTime(row.executionTime) }}
            </span>
          </template>
        </el-table-column>

        <el-table-column label="操作时间" width="200">
          <template #default="{ row }">
            {{ formatDateTime(row.operationTime, 'YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleViewDetail(row)" link>
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[15, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.log-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 10px;

  .controller-container {
    border-radius: 10px;
    background-color: #fff;
  }

  .table-container {
    width: 100%;
    height: 100%;
    flex: 1;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border-radius: 10px;
    padding: 15px;
    overflow: hidden;

    .el-table {
      flex: 1;
    }

    .pagination-container {
      margin-top: 15px;
      display: flex;
      justify-content: flex-end;
    }
  }
}

.slow-request {
  color: #f56c6c;
  font-weight: bold;
}

.log-detail {
  .detail-section {
    margin-top: 20px;

    h4 {
      margin: 0 0 10px 0;
      color: #303133;
      font-size: 14px;
      font-weight: 600;
    }

    .json-textarea {
      font-family: 'Courier New', Courier, monospace;

      :deep(.el-textarea__inner) {
        background-color: #f8f9fa;
        border: 1px solid #e9ecef;
        font-size: 12px;
        line-height: 1.4;
      }
    }

    .error-textarea {
      :deep(.el-textarea__inner) {
        background-color: #f8f9fa;
        border: 1px solid #e9ecef;
        font-size: 12px;
        line-height: 1.4;
        color: #606266;
      }

      &.has-error {
        :deep(.el-textarea__inner) {
          background-color: #fef0f0;
          border: 1px solid #fab6b6;
          color: #f56c6c;
        }
      }
    }
  }
}
</style>
